package cn.wolfcode.rbac.web.interceptor;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.util.RequiredPermission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class SerurityInIntercptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Employee current = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        if (current.isAdmin()){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (!method.isAnnotationPresent(RequiredPermission.class)){
            return true;
        }
        //3 如果有看是否在该用户所拥有的权限集合中
        RequiredPermission requiredPermission = method.getAnnotation(RequiredPermission.class);
        String expression = requiredPermission.values()[1];
        List<String> expressions = (List<String>) request.getSession().getAttribute("EXPRESSION_IN_SESSION");
        if (expressions.contains(expression)){
            return true;
        }
        //4 如果不在跳转到没有权限的界面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;

    }



}
